<template>
  <div>
    <el-dialog v-model="open" title="上传" width="400px" append-to-body @close="close">
      <el-upload ref="uploadRef" :limit="1" accept=".doc, .docx" :headers="headers" :action="importUrl"
        :data="uploadParams.params" :disabled="isUploading" :before-upload="handleFileBeforeUpload"
        :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError" :on-success="handleFileSuccess"
        :auto-upload="true" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入doc、docx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <!-- 文件列表 -->
      <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
        <li class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList"
          :key="file.attachId">
          <el-row>
            <el-col :span="20">
              <el-link @click="handleDownload(file)" :underline="false" target="_blank">
                <span class="el-icon-document">{{ file.attachName }} </span>
              </el-link>
            </el-col>
            <el-col :span="4">
              <el-link :underline="false" @click="handleDelete(index, file)" type="danger">删除</el-link>
            </el-col>
          </el-row>
        </li>
      </transition-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button plain @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { getToken } from "@/utils/auth"

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  uploadParams: {
    type: Object,
    default: () => ({ url: '/attachment/uploadFile' })
  }
})

const importUrl = computed(() => import.meta.env.VITE_APP_BASE_API + props.uploadParams.url)
const emits = defineEmits(['update:open', 'importSuccess', 'confirm'])
const { proxy } = getCurrentInstance()
const isUploading = ref(false)
const headers = { token: "token " + getToken() }

// 文件上传前处理
function handleFileBeforeUpload(file) {
  let fileExtension = "";
  if (file.name.lastIndexOf(".") > -1) {
    fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1)
  }
  if (!['doc', 'docx'].some(item => item == fileExtension)) {
    proxy.$modal.msgError(`文件格式不正确, 请上传doc、docx格式的文件!`)
    return false
  }
  const isLt = file.size / 1024 / 1024 < 100;
  if (!isLt) {
    proxy.$modal.msgError(`上传文件大小不能超过 100 MB!`)
    return false
  }
  if (file.size == 0) {
    proxy.$modal.msgError(`上传文件大小不能为空！`)
    return false
  }
  proxy.$modal.loading("正在导入文件，请稍候...")
  return true
}

// 文件上传中处理
const handleFileUploadProgress = (event, file, fileList) => {
  isUploading.value = true
}
// 上传失败
const handleFileUploadError = (err) => {
  proxy.$modal.closeLoading()
  proxy.$modal.msgError("导入文件失败")
}
// 文件上传成功
const handleFileSuccess = (response, file) => {
  isUploading.value = false
  proxy.$modal.closeLoading()
  proxy.$refs["uploadRef"].handleRemove(file)
  if (response.code == 200) {
    fileList.value = response.data
    // proxy.$modal.msgSuccess('上传成功!')
    emits('importSuccess')
  } else {
    // proxy.$modal.msgError('上传失败!')
  }
}

// 确定
const fileList = ref([])
const submitFileForm = () => {
  // proxy.$refs["uploadRef"].submit()
  if(fileList.value.length == 0){
    proxy.$modal.msgWarning('请上传doc、docx格式的文件！')
    return
  }
  // emits('confirm', fileList.value[0].attachId)
  emits('confirm', fileList.value[0])
}
// 下载文件
function handleDownload(file) {
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(file.attachId);
}
// 删除
function handleDelete(index, file) {
  fileList.value.splice(index, 1);
  emit('delFile', '');
}

const close = () => {
  emits('update:open', false)
  fileList.value = []
}
</script>
<style scoped></style>